/*global $, jQuery, console, alert*/
/*
 *{titles}  : 右侧悬浮工具条
 *{author}  : daFei
 **/

var rrs = rrs ||{};
var uid = "";
var uname = "";

(function ($) {
  'use strict';
  var rightSideBar = {
    init: function() {
      this.createDOM();
      this.elements();
      this.events();
    },
    createDOM: function() {
      var domElem = '';

      domElem += '<div class="right-sidebar">';
      domElem += '<a href="javascript:void(0);" class="back-top"><i class="icon-font icon-top"></i>顶部</a>';
      if (typeof ntalkerId != 'undefined') {
    	  domElem += '<a href="javascript:NTKF.im_openInPageChat(\'' + ntalkerId + '_9999\');"><i class="icon-font icon-kf"></i>在线客服</a>';
      } else {
    	  domElem += '<a href="javascript:NTKF.im_openInPageChat(\'he_1000_9999\');"><i class="icon-font icon-kf"></i>在线客服</a>';
      }
      domElem += '<a href="javascript:location.href=rrs.baseCartUrl"><i class="icon-font icon-cart"></i>购物车</a>';
      domElem += '<a href="javascript:void(0);" class="app-mobile"><i class="icon-font icon-qr-code"></i>手机版</a>';
      domElem += '<span>扫描二维码<br>访问手机日日顺<img src="'+rrs.shoujiUrl+'"><em><b></b></em></span>';
      domElem += '</div>';

      $('body').append(domElem);
    },
    elements: function() {
      this.self = $('.right-sidebar');
      this.backTop = this.self.find('.back-top');
      this.appMobile = this.self.find('.app-mobile');
      this.appMobileQrCode = this.self.find('span');
    },
    events: function() {
      var
        that = this,
        timer = null;

      $(window).on('scroll', function() {
        //noinspection JSValidateTypes
        var top = $(this).scrollTop();
        that.backTop[0].style.display = top > 50 ? 'block' : 'none';
      });

      this.backTop.click(function() {
        $('html, body').stop().animate({scrollTop: 0});
      });

      this.appMobile.mouseenter(function() {
        clearTimeout(timer);
        timer = null;
        that.appMobileQrCode.show();
      });

      this.appMobile.mouseleave(function() {
        timer = setTimeout(function() {
          that.appMobileQrCode.hide();
        }, 100);
      });

      this.appMobileQrCode.mouseenter(function() {
        clearTimeout(timer);
        timer = null;
        that.appMobileQrCode.show();
      });

      this.appMobileQrCode.mouseleave(function() {
        timer = setTimeout(function() {
          that.appMobileQrCode.hide();
        }, 100);
      });
    }
  };

  rightSideBar.init();
}(jQuery));

/*
 *{titles}  : headerBar
 *{author}  : daFei
 **/

(function ($) {
  'use strict';
  var headerBar = {
    init: function() {
      this.hover();
      this.hotRank();
      this.getPos();
      this.getCity('.city-list');
      this.events();
    },
    hover: function() {
      $('.js-item').hover(function() {
        var len = $(this).is(function() {
          return $('.drop-layer', this).length;
        });

        if (len) {
          $(this).addClass('active');
        }
      }, function() {
        $(this).removeClass('active');
      });
    },

    hotRank: function() {
    	/*
		####### author:ddl;
		####### date:20151120
		 */
		var $hotrank = $(".mainhot");
		$hotrank.hover(function(){
			$(this).find(".hot-rank").css("display","block");
		},function(){
			$(this).find(".hot-rank").css("display","none");
		});
		//tab
		var $jstab = $('#js-tab');
		var $jscnt = $('#js-cnt');
		var sList = $jstab.children('span');
		var rList = $jscnt.children('ul');
		for(var i = 0;i < sList.length;i++){
			sList[i].index = i;
			rList[i].index = i;

			sList[i].onclick = function(){
				for(var j = 0;j < sList.length;j++){
					$(sList[j]).removeClass('active');
					$(rList[j]).removeClass('selected');
				}
				if(this.index == 0){
					$(this).addClass('active').css("border-left","none");
					$(sList[1]).height("31px");
					$(sList[2]).height("31px");
				}
				else if(this.index == 2){
					$(this).addClass('active').css("border-right","none");
					$(sList[0]).height("31px");
					$(sList[1]).height("31px");
				}
				else{
					$(this).addClass('active');
					$(sList[0]).height("31px");
					$(sList[2]).height("31px");
				}
				$(this).height("30px");
				$(rList[this.index]).addClass('selected');
			}
		};
		//商品
		var lis = $(".goods").children('li');
		$(lis).each(function(){
			$(this).hover(function(){
				$(lis).find("dl").hide();
				$(lis).find("a>span").show();
				$(lis).find("p").removeClass('pactive')
				$(lis).removeClass("hoveron");
				$(this).addClass('hoveron');
				$(this).find("dl").show();
				$(this).find("a>span").hide();
				$(this).find("p").addClass("pactive");
			})
		});

		$(window).resize(function() {
		    var dbw = document.body.clientWidth;
			if(dbw < 1264 && dbw >0){
				$(".header-menu .menu-nav span.common").hide();
			}
			else if(dbw > 1263)
			{
				$(".header-menu .menu-nav span.common").show();
			}
		});

      },

    getPos: function() {
        var that = this;
        var currentDomain = document.domain;
        if (currentDomain.split(".").length > 2) {
            currentDomain = currentDomain.substring(currentDomain.indexOf(".") + 1, currentDomain.length)
        }
        $.ajax({//加载顶部右侧用户登录信息
            type:"GET",
            url: "http://member." + currentDomain + "/headLoginAjax",
            dataType: "jsonp",
            jsonp: "callback",
            success: function (data) {
                // sso
                if (data.ssoUrl != undefined) {
                    var baseUrl = decodeURIComponent(data.ssoUrl);
                    baseUrl = baseUrl + "?rem="+data.rem + "&loginName=" + data.loginName + "&token=" + data.ssoToken + "&returnUrl=";
                    $("<iframe></iframe>").attr("src", baseUrl).appendTo($('body'));
                }

            	var ntalkerIdFoo = 'he_1000';
            	
            	if (typeof ntalkerId != 'undefined') {
            		ntalkerIdFoo = ntalkerId;
            	}
            	
            	if (typeof ntalkerId == 'undefined' || ntalkerId == 'he_1000') {
                    if(typeof ntkfProductId == 'undefined'){
                        window.NTKF_PARAM = window.NTKF_PARAM || {
                            siteid: 'he_1000',
                            settingid: 'he_1000_9999',
                            uid: data.uid,
                            uname: data.uname,
                            userlevel: '0'
                        }
                    }else{
                        window.NTKF_PARAM = window.NTKF_PARAM || {
                            siteid: 'he_1000',
                            settingid: 'he_1000_9999',
                            itemid: ntkfProductId,
                            uid: data.uid,
                            uname: data.uname,
                            userlevel: '0'
                        }
                    }
            	} else {
                    if(typeof ntkfProductId == 'undefined'){
                        window.NTKF_PARAM = window.NTKF_PARAM || {
                            siteid: 'he_1000',
                            sellerid: ntalkerId,
                            settingid: 'he_1000_9999',
                            uid: data.uid,
                            uname: data.uname,
                            userlevel: '0'
                        }
                    }else{
                        window.NTKF_PARAM = window.NTKF_PARAM || {
                            siteid: 'he_1000',
                            sellerid: ntalkerId,
                            settingid: 'he_1000_9999',
                            itemid: ntkfProductId,
                            uid: data.uid,
                            uname: data.uname,
                            userlevel: '0'
                        }
                    }
            	}

                var s = document.createElement('script');
                s.type = 'text/javascript';
                s.src = 'http://dl.ntalker.com/js/b2b/ntkfstat.js?siteid=he_1000';
                document.body.appendChild(s);

                $('.header-bar').find('.user').html(data.data);
                var shopId = data.shopId;
                if (null != shopId && 'undefind' != shopId && "" != shopId) {
                    $('#js-favShangj').html('<a href="'+rrs.shopDomain+'/index.html" rel="nofollow">商家中心</a>');
                } else {
                    $('#js-favShangj').html('<a href="'+rrs.shopDomain+'/settle.html" rel="nofollow">商家入驻</a>');
                }

                if ($(".user-not-logged") != undefined  && $(".user-not-logged").html() != undefined) {
                    $('#js-favShangj').html('<a href="'+rrs.shopDomain+'/centerIndex.html" rel="nofollow">商家入驻</a>');
                }
                // add by suijialin 非B2B用户不显示在线采购链接 begin 20160113
                var memberType = data.memberType;
                if (null == memberType || 'undefind' == memberType || "" == memberType || "b2b" !=memberType) {
                    $('#js-favPingp').parent('li').html('');
                }
                // add by suijialin 非B2B用户不显示在线采购链接 begin 20160113

                $.ajax({ //加载顶部左侧当前城市信息，v3首页还会根据当前城市id加载团购信息

                    type:"GET",

                    url: "http://member." + currentDomain + "/currCityAjax?r=" + Math.random(),
                    //url: "http://localhost:8082"+"/currCityAjax?r=" + Math.random(),

                    dataType: "jsonp",

                    jsonp: "callback",

                    cache: false,

                    success: function (data) {
                        if (data.success) {
                            $('#city').html(data.data.cityName);
                            $('#city').attr('name',data.data.cityId);
                            $('#city-code').val(data.data.cityCode);
                            that.initExperStore(data.data.cityCode);

                            if($("#js-dueMember").length>0){
                               that.initIfShowIconForDueMember(data.data.cityCode);
                            }

                        }
                    }
                });
            }
        });
    },
    getCity: function(obj) {

        var that =this;

        if ($('.city').length) {

            var $citybox = $('.city-list');

            var markPosArr={mark:0,arr:[]};//new arr save city mark

            $('#city').hover(function() {

                if (markPosArr.mark==0) {//初次加载
                    $.ajax({//load city list

                        type:"GET",

                        url: rrs.ehaierBaseDomain+"getRegons",
                        //url: "http://localhost:8081/"+"getRegons",
                        dataType: "jsonp",

                        jsonp: "callback",

                        success : function (msg) {

                            $(msg.data).appendTo($citybox);

                            var nowCity = $('#city').text();
                            var $city = $citybox.find('dd:contains("'+nowCity+'")');
                            var provinceId = $city.attr("provinceid");

                            $citybox.find('dd span:contains("'+nowCity+'")').addClass('active');
                            $("[regionId="+provinceId+"]").parent().addClass('active');
                           // $city.show();

                            $("[name=provinceA]").each(function(i, item){
                                $(item).click(function() {
                                    $("[name=provinceA]").parent().removeClass("active");
                                    $(this).parent().addClass('active');

                                    $("[name=cityDd]").hide();
                                    $("[provinceId="+$(this).attr("regionId") +"]").show();

                                    /*计算偏移量 开始*/
                                    //var _left = ($(this).offset().left - 200.390625);
                                    var _left = $(this).position().left + 5;
                                    $("[provinceId="+$(this).attr("regionId") +"]").find("b").css({
                                        "left" : _left + "px"
                                    });
                                    /*计算偏移量 结束*/
                                });
                            });

                            $citybox.find('a').click(function () {
                                var href = $(this).attr('href');
                                // TODO       检测代码确认是否还要
                                // _gaq.push(['_trackPageview',href]);
                            });
                        }
                    });
                }
                //$citybox.show();
                markPosArr.mark = 1;
                return false;
            });
        }
    },
    
    initExperStore:function(cityCode){
        var that = this;

        var cityId = cityCode;
        if(cityCode.substr(2, 4) === '0000'){
            cityId = cityCode.substr(0, 2) + '0100';
        }

        var url = rrs.baseDomain+"ixv5/getExperienceAndMuseumByCity";
        $.ajax({
            type: "GET",
            url: url,
            dataType: "jsonp",
            jsonp: "callback",
            data: { city: cityId },
            success: function(data) {
                var hrefList=new Array();
                var srcList=new Array();
                that.printExperMallInfo(data,true,hrefList,srcList);
                $('.tyg-slide a').eq(0).attr("href",hrefList[0]);
                $('.tyg-slide img').eq(0).attr("src",srcList[0]);
                if ( $('#js-tyg-slide').length ) {
                    $('#js-tyg-slide').slide({
                        isLoop: false,
                        isAuto: false,
                        isMarker: false,
                        callbackCurIndex:function(curIndex){
                            if(hrefList && hrefList[curIndex]){
                                $('.tyg-slide a').eq(0).attr("href",hrefList[curIndex]);
                                $('.tyg-slide img').eq(0).attr("src",srcList[curIndex]);
                            }
                        }
                    });
                }
            },
            error: function(e) {
            	that.printExperMallInfo("",false);
                if ( $('#js-tyg-slide').length ) {
                    $('#js-tyg-slide').slide({
                        isLoop: false,
                        isAuto: false,
                        isMarker: false
                    });
                }
              return false;
            }
        });
    },
    
    
     initIfShowIconForDueMember:function(cityCode){
		if(cityCode == "" || cityCode == null){
			cityCode = "370200";
		}else if(cityCode == "110000" ||cityCode == "120000" ||cityCode == "310000" ||cityCode == "500000" ){
			cityCode = parseInt(cityCode) + 100;
		}
	    var exsitedUrl = "/exisitedShop?cityCode="+cityCode;
	    $.ajax({
	   	    type: 'get',   
	   		url:exsitedUrl,
	   		dataType: "json",
	   		cache: false,    		
	   		async:false,
	   		success: function(data, status){
	   			if(data.message == "Y"){
	   				$("#js-dueMember").show();
	   			}else{
	   				$("#js-dueMember").hide();
	   			}
	       },
	      error: function(XMLHttpRequest, textStatus, exception){
	      	alert(XMLHttpRequest.status+','+XMLHttpRequest.readyState+','+textStatus);
	          alert(msgAjaxErrorForRequest); 
	      }
	    });	
    },
    

    printExperMallInfo:function(result,flag,hrefList,srcList){
    	var data = null;
    	if(flag){
            data = result.stores;
        }
    	var $experStore = $('#experience-store');
        if (flag && data != null && data.length > 0) {
            var i=0;
            $.each(data, function(index, experMall) {
                $experStore.append("<li><img src='" + experMall.imageUrl + "' alt='' >"
                        + "<p>"
                        + "<strong>" + experMall.name + "</strong>"
                        + "<br> 联系电话：" + experMall.phone + "&nbsp;&nbsp;" + experMall.mobile
                        + "<br> 展馆地址：" + experMall.address
                        + "</p>"
	                    + "<a href='" + experMall.shopUrl + "' target='_blank'><i class='icon-font icon-cancel'></i>查看本店商品</a>"
	                    + "<a href='http://shui.rrs.com/regionMap?shopId=" + experMall.shopId + "' target='_blank'><i class='icon-font icon-location'></i>查看地图</a></li>");
                if(typeof experMall.hrefUrl!='undefined'){
                    hrefList[i]=experMall.hrefUrl;
                    srcList[i]=experMall.imageUrlB;
                }else{
                    hrefList[i]="http://shui.rrs.com/regionStore";
                    srcList[i]="http://c.rrsjk.com/shoppingmall/resources/css/rrs/img/exper.jpg";
                }
                i++;
            })
        }else{
        	$experStore.append("<li><img src='http://img01.rrs.com/rrs_photo/20150323/store_1.jpg' alt='' >"
	                    + "<p>"
	                    + "<strong>日日顺净水体验馆(上海店)</strong>"
	                    + "<br> 联系电话：021-62868220  18801774279"
	                    + "<br> 展馆地址：嘉定区沪宜公路3188号"
	                    + "</p>"
	                    + "<a href='http://v2.rrs.com/shops/53302271' target='_blank'><i class='icon-font icon-cancel'></i>查看本店商品</a>"
	                    + "<a href='http://shui.rrs.com/regionMap?shopId=43' target='_blank'><i class='icon-font icon-location'></i>查看地图</a></li>"
	                    + "<li><img src='http://img01.rrs.com/rrs_photo/20150323/store_1.jpg' alt='' >"
	                    + "<p>"
	                    + "<strong>上海蜀葵实业</strong>"
	                    + "<br> 联系电话：13003139431"
	                    + "<br> 展馆地址：上海市沪太路3663号"
	                    + "</p>"
	                    + "<a href='http://v2.rrs.com/shops/66226531' target='_blank'><i class='icon-font icon-cancel'></i>查看本店商品</a>"
	                    + "<a href='http://shui.rrs.com/regionMap?shopId=87' target='_blank'><i class='icon-font icon-location'></i>查看地图</a></li>");
            hrefList[0]="http://shui.rrs.com/regionStore";
            srcList[0]="http://c.rrsjk.com/shoppingmall/resources/css/rrs/img/exper.jpg";
        }
    },
    
  _toggleCity: function(regionId) {
      $.ajax({
          type:"GET",

          url: rrs.memberDomain+"/toggle?regionId="+regionId,

          dataType: "jsonp",

          jsonp: "callback"
      });
  },
    addFav: function(url, title) {
      try {
        window.external.addFavorite(url, title);
      } catch (e) {
        try {
          window.sidebar.addPanel(url, title, '');
        } catch (ex) {
          alert('加入收藏失败，请使用CTRL + D进行添加');
        }
      }
    },
    events: function() {
      var
        self = this,
        subMenu = $('.menu-sub');

      $('#js-fav').on('click', function() {
        self.addFav(window.location, document.title);
      });

      if (subMenu.find('.sub-bd').css('display') === 'none') {
        subMenu.hover(function() {
          $(this).find('.sub-bd').css('display', 'block');
        }, function() {
          $(this).find('.sub-bd').css('display', 'none');
        });
      }
    }
  };

  headerBar.init();
}(jQuery));


//关注微博和微信
(function($) {
  'use strict';
  function conf_attention (obj) {
    var self = $(obj);

    self.find('i').mouseenter(function(e) {
      if (e.target.className.split(' ')[1] === 'icon-sina') {
        self.find('.quick-code-bd').css('marginLeft', '-62px');
        self.find('span').html('关注日日顺官方微博');
        self.find('img').attr('src', rrs.baseDomain + 'resources/css/rrs/img/wb.gif');
        self.find('.quick-code-bd').show();
      } else {
        self.find('.quick-code-bd').css('marginLeft', '-36px');
        self.find('span').html('关注日日顺官方微信');
        self.find('img').attr('src', rrs.baseDomain + 'resources/css/rrs/img/wx.gif');
        self.find('.quick-code-bd').show();
      }
    });

    self.mouseleave(function() {
      self.find('.quick-code-bd').hide();
    });
  }

  conf_attention('.quick-gz');
}(jQuery));


//搜索框
(function ($) {
  var searchBoxGroup = $('.search-box-group');

  searchBoxGroup.hover(function() {
    $(this).find('li').eq(1).show();
  }, function() {
    $(this).find('li').eq(1).hide();
  });

  searchBoxGroup.find('li').click(function() {
    $(this).prependTo(searchBoxGroup);
    searchBoxGroup.find('li').eq(1).hide();
  });

  var sBtn = $('#header').find('.search-btn');

  sBtn.click(function() {
    var currentSearchBoxGroupValue = $('.search-box-group').find('li').find('a').eq(0).html();
    var header = $('#header');
    var form = header.find('form');
    var input = header.find('input[type="text"]');
    if (currentSearchBoxGroupValue === '店铺') {
      input.attr('name', 'q');
      form.attr('action', 'http://search.rrsjk.com/shopSearch.html');
    } else {
      input.attr('name', 'k');
      form.attr('action', rrs.ehaierBaseDomain+'/s');
    }
  });
}(jQuery));


$(document).ready(function(){
	   var c_name = 'JSESSIONID';
	   if(document.cookie.length>0){
	      c_start=document.cookie.indexOf(c_name + "=")
	      if(c_start!=-1){ 
	        c_start=c_start + c_name.length+1; 
	        c_end=document.cookie.indexOf(";",c_start);
	        if(c_end==-1);
		c_end=document.cookie.length;
	        var sessonid = unescape(document.cookie.substring(c_start,c_end));
		document.cookie="YZHD_SESSIONID="+sessonid ;
	      }
	   }
	 });

(function() {
    $.ajax({
        type : "GET",
        url : rrs.memberDomain+"/getBuddiesJson.html",
        dataType: "jsonp",
        success : function(data) {
            if (data && null != data.data) {
            	// TODO 显示气泡
            	var rrsflag=0;
            	var pointflag=0;
            	var ordersflag=0;
            	for(var i=0; i<data.data.length; i++){
        			if(data.data[i] == "point"){
        				pointflag=1;
        				rrsflag=1;
        			}
        			if(data.data[i] == "orders"){
        				ordersflag=1;
        				rrsflag=1;
        			}
        			
        		}
            	if(rrsflag==1){
            		$("#rrsflag").show();
            	}
            	if(pointflag==1){
            		$("#pointflag").show();
            	}
            	if(ordersflag==1){
            		$("#ordersflag").show();
            	}
                
            }else{
                //$.sobox.alert('提示', data.message);
            }
        }
    });
})();
